﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.CUiTcEndModelingForm
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using DnProcessSimulateCommands.EndModelingEntityLevel;
using DnProcessSimulateCommands.TcCommands.TcEndModeling;
using EngineeringInternalExtension;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Resources;
using System.Windows.Forms;
using Tecnomatix.Engineering;
using Tecnomatix.Engineering.CommandParameters;
using Tecnomatix.Engineering.Ui;
using Tecnomatix.Planning;


namespace DnProcessSimulateCommands;

public class CUiTcEndModelingForm : TxForm
{
  private TxTypeFilter m_processFilter = new TxTypeFilter(typeof (TxTcProcess));
  private IContainer components;
  private RadioButton m_editJtOnObject;
  private RadioButton m_editJtOnProcess;
  private Label m_txt;
  private TxObjComboBoxCtrl m_process;
  private RadioButton m_reloadComponent;
  private Button m_cancelButton;
  private Button m_okButton;
  private CCoTcEndModelingCmd m_cmd;
  private ITxObject m_object;

  public CUiTcEndModelingForm(CCoTcEndModelingCmd cmd)
  {
    this.InitializeComponent();
    this.m_cmd = cmd;
    this.RegisterToUnloadDocumentEvent();
    cmd.IsDialogOpen = true;
    this.m_object = ((Collection<ITxObject>) TxApplication.ActiveSelection.GetAllItems())[0];
  }

  public virtual void OnInitTxForm()
  {
    this.initRadioButtons();
    this.initComboBox();
    this.m_okButton.Enabled = true;
    if (!this.m_editJtOnProcess.Checked || this.m_process.IsValid())
      return;
    this.m_okButton.Enabled = false;
  }

  private void initRadioButtons()
  {
    this.m_editJtOnObject.Enabled = !this.shouldDisableEditJtOnObject();
    this.m_editJtOnProcess.Enabled = this.m_process.Enabled = !this.ShouldDisableOnProcess();
    CUiTcEndModelingForm.EndModelingType endModelingType = this.LoadDialogConfiguration();
    if (endModelingType == CUiTcEndModelingForm.EndModelingType.JtOnProcess)
    {
      if (this.m_editJtOnProcess.Enabled)
      {
        this.m_editJtOnProcess.Checked = true;
        this.m_process.Enabled = true;
        this.m_process.Focus();
      }
      else
        this.m_reloadComponent.Checked = true;
    }
    else
    {
      this.m_process.Enabled = false;
      this.m_process.HideErrorWindow();
      this.m_okButton.Focus();
      if (endModelingType == CUiTcEndModelingForm.EndModelingType.JtOnObject && this.m_editJtOnObject.Enabled)
        this.m_editJtOnObject.Checked = true;
      else
        this.m_reloadComponent.Checked = true;
    }
  }

  private bool shouldDisableEditJtOnObject()
  {
    bool flag = false;
    if (!flag)
      flag = this.m_object == null;
    if (!flag)
      flag = this.m_object is ITxProcessModelObject processModelObject && processModelObject.PlanningRepresentation is TxPlanningPart;
    if (!flag)
      flag = !this.m_object.CanBeModified;
    if (!flag)
    {
      try
      {
        flag = !TxTcUtilities.CanUpdateItemRevisionOnEndModeling(this.m_object);
      }
      catch (TxException ex)
      {
        TxApplication.LogWriter.WriteExceptionLine((Exception) ex);
        flag = true;
      }
    }
    return flag;
  }

  private void SelectDefaultComboBoxObject()
  {
    ITxObject itxObject = (ITxObject) null;
    TxTcProcess rootProcess = this.getRootProcess();
    if (TxTcProcess.op_Inequality(rootProcess, (ITxObject) null) && rootProcess.CanBeModified)
      itxObject = (ITxObject) rootProcess;
    else if (((Collection<ITxObject>) this.m_process.Items).Count > 0)
      itxObject = ((Collection<ITxObject>) this.m_process.Items)[0];
    this.m_process.SelectObject(itxObject);
  }

  private bool ShouldDisableOnProcess()
  {
    bool flag = true;
    foreach (ITxObject allDescendant in (Collection<ITxObject>) TxApplication.ActiveDocument.OperationRoot.GetAllDescendants((ITxTypeFilter) this.m_processFilter))
    {
      if (allDescendant != null && allDescendant.CanBeModified)
        flag = false;
    }
    return flag;
  }

  private void initComboBox()
  {
    this.m_process.SetValidator((ITxValidator) new CApTcEndModelingProcessValidator((ITxTypeFilter) this.m_processFilter));
    foreach (ITxObject allDescendant in (Collection<ITxObject>) TxApplication.ActiveDocument.OperationRoot.GetAllDescendants((ITxTypeFilter) this.m_processFilter))
    {
      if (allDescendant is TxTcProcess && allDescendant.CanBeModified)
        this.m_process.AddItem(allDescendant.Name, allDescendant);
    }
    this.SelectDefaultComboBoxObject();
  }

  private TxTcProcess getRootProcess()
  {
    TxObjectList directDescendants = TxApplication.ActiveDocument.OperationRoot.GetDirectDescendants((ITxTypeFilter) new TxTypeFilter(typeof (ITxCompoundOperation)));
    return ((Collection<ITxObject>) directDescendants).Count > 0 ? ((Collection<ITxObject>) directDescendants)[0] as TxTcProcess : (TxTcProcess) null;
  }

  private void CUiTcEndModelingForm_FormClosed(object sender, FormClosedEventArgs e)
  {
    this.m_cmd.IsDialogOpen = false;
    this.UnRegisterFromUnloadDocumentEvent();
    this.SaveDialogConfiguration();
  }

  private void m_process_TypeInvalid(object sender, EventArgs e)
  {
    if (!this.m_editJtOnProcess.Checked)
      return;
    this.m_okButton.Enabled = false;
  }

  private void m_process_TypeValid(object sender, EventArgs e) => this.m_okButton.Enabled = true;

  private void m_process_Picked(object sender, TxObjComboBoxCtrl_PickedEventArgs args)
  {
    if (this.m_process.Object != null)
      this.m_okButton.Enabled = true;
    else
      this.m_okButton.Enabled = false;
  }

  private void m_editJtOnProcess_CheckedChanged(object sender, EventArgs e)
  {
    if (this.m_editJtOnProcess.Checked)
    {
      this.m_process.Enabled = true;
      this.m_process.Focus();
    }
    else
    {
      this.m_process.Enabled = false;
      this.m_process.HideErrorWindow();
      this.m_okButton.Focus();
    }
    if (this.m_editJtOnProcess.Checked && !this.m_process.IsValid())
      this.m_okButton.Enabled = false;
    else
      this.m_okButton.Enabled = true;
  }

  private void m_cancelButton_Click(object sender, EventArgs e) => ((Form) this).Close();

  private void RegisterToUnloadDocumentEvent()
  {
    TxApplication.ActiveDocument.Unloading += new TxDocument_UnloadingEventHandler(this.OnUnloadDocument);
  }

  private void UnRegisterFromUnloadDocumentEvent()
  {
    TxApplication.ActiveDocument.Unloading -= new TxDocument_UnloadingEventHandler(this.OnUnloadDocument);
  }

  private void OnUnloadDocument(object sender, TxDocument_UnloadingEventArgs args)
  {
    ((Form) this).Close();
  }

  private void m_okButton_Click(object sender, EventArgs e)
  {
    ((Form) this).Close();
    if (this.m_editJtOnObject.Checked)
      CUiTcEndModelingForm.InvokeEndModeling((Action) (() => CUiTcEndModelingForm.EndModelingOnObject(this.m_object)));
    else if (this.m_editJtOnProcess.Checked)
    {
      CUiTcEndModelingForm.InvokeEndModeling((Action) (() =>
      {
        this.storeJtOnProcess();
        TxApplication.RefreshDisplay();
      }));
    }
    else
    {
      if (!this.m_reloadComponent.Checked)
        return;
      CUiTcEndModelingForm.InvokeEndModeling((Action) (() => this.reloadComponent()));
    }
  }

  private static void InvokeEndModeling(Action action)
  {
    try
    {
      action();
    }
    catch (TxTcFailedWriting3DDatasetException ex)
    {
      int num = (int) TxMessageBox.Show(string.Format(StringTable.END_MODELING_FAILED_DATASET, (object) ex.SourceObject.Name), StringTable.END_MODELING_CMD_NAME, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    }
  }

  private static void EndModelingOnObject(ITxObject @object)
  {
    CApEMEndModelingEntityLevelApp modelingEntityLevelApp = new CApEMEndModelingEntityLevelApp(@object as ITxComponent);
    if (!modelingEntityLevelApp.ComponentEndModeling())
      return;
    CUiTcEndModelingForm.storeJtOnObject(@object, modelingEntityLevelApp.ReloadInDetailRepresentation, modelingEntityLevelApp.ReloadPMIs, modelingEntityLevelApp.ReloadWithCommand);
    TxApplication.RefreshDisplay();
  }

  public static void PerformEndModelingOnObject(ITxObject @object)
  {
    CUiTcEndModelingForm.InvokeEndModeling((Action) (() => CUiTcEndModelingForm.EndModelingOnObject(@object)));
  }

  public static void storeJtOnObject(
    ITxObject @object,
    bool relaodInDetailRepresentation,
    bool reloadPMI,
    bool reloadWithCommand)
  {
    Cursor current = Cursor.Current;
    Cursor.Current = Cursors.WaitCursor;
    TxLocalStorage storageObject = (@object as ITxStorable).StorageObject as TxLocalStorage;
    if (TxStorage.op_Inequality((TxStorage) storageObject, (TxStorage) null))
    {
      TxApplication.ActiveDocument.UndoManager.ClearAllTransactions();
      TxRepresentationLevel representationLevel = relaodInDetailRepresentation ? (TxRepresentationLevel) 5 : (TxRepresentationLevel) 4;
      TxComponentEx.CopyScopeToRevision(storageObject, representationLevel, reloadPMI);
      if (reloadWithCommand)
        CUiTcEndModelingForm.ReloadWithCommand(@object, relaodInDetailRepresentation, reloadPMI);
      TxApplication.ActiveDocument.UndoManager.ClearAllTransactions();
    }
    Cursor.Current = current;
  }

  private static void ReloadWithCommand(
    ITxObject @object,
    bool relaodInDetailRepresentation,
    bool reloadPMI)
  {
    CUiTcEndModelingForm.ReloadEntityLevelWithCommand(@object, relaodInDetailRepresentation);
    CUiTcEndModelingForm.ReloadPMIInfoWithCommand(@object, reloadPMI);
  }

  private static void ReloadPMIInfoWithCommand(ITxObject @object, bool reloadPMI)
  {
    TxMultipleObjectParameters reloadParam = CUiTcEndModelingForm.GetReloadParam(@object);
    if (reloadPMI)
      TxApplication.CommandsManager.ExecuteCommand("ComponentOperations.LoadComponentsAtPMILevel", (object) reloadParam);
    else
      TxApplication.CommandsManager.ExecuteCommand("ComponentOperations.UnloadComponentsFromPMILevel", (object) reloadParam);
  }

  private static TxMultipleObjectParameters GetReloadParam(ITxObject @object)
  {
    TxMultipleObjectParameters reloadParam = new TxMultipleObjectParameters();
    TxObjectList txObjectList = new TxObjectList(1);
    ((Collection<ITxObject>) txObjectList).Add(@object);
    reloadParam.Objects = txObjectList;
    return reloadParam;
  }

  private static void ReloadEntityLevelWithCommand(
    ITxObject @object,
    bool relaodInDetailRepresentation)
  {
    TxMultipleObjectParameters reloadParam = CUiTcEndModelingForm.GetReloadParam(@object);
    if (relaodInDetailRepresentation)
      TxApplication.CommandsManager.ExecuteCommand("ComponentOperations.LoadComponentsAtEntityLevel", (object) reloadParam);
    else
      TxApplication.CommandsManager.ExecuteCommand("ComponentOperations.UnloadComponentsFromEntityLevel", (object) reloadParam);
  }

  private void reloadComponent()
  {
    new TxCommandManager().ExecuteCommandByCommandProgId("CCoEDOReloadComponentCmd", (object) TxApplication.ActiveSelection.GetItems(), false);
  }

  private void storeJtOnProcess()
  {
    Cursor current = Cursor.Current;
    Cursor.Current = Cursors.WaitCursor;
    TxLocalStorage storageObject = (this.m_object as ITxStorable).StorageObject as TxLocalStorage;
    if (TxStorage.op_Inequality((TxStorage) storageObject, (TxStorage) null))
    {
      try
      {
        string str1 = storageObject.SaveComponent();
        ITxPlanningObject planningRepresantation = this.GetPlanningRepresantation(this.m_process.Object);
        if (planningRepresantation != null)
        {
          string str2;
          try
          {
            str2 = DateTime.Now.ToString("dd-MMM-yyyy H:mm:ss", (IFormatProvider) CultureInfo.CreateSpecificCulture("en-US"));
          }
          catch (Exception ex)
          {
            str2 = DateTime.Now.ToString("dd/MM/yyyy H:mm:ss");
          }
          string str3 = $"{this.m_object.Name} {str2}";
          if (str3.Length > 32 /*0x20*/)
            str3 = $"{this.m_object.Name.Substring(0, 32 /*0x20*/ - str2.Length - 2)} {str2}";
          TxTcFileAttachmentData fileAttachmentData = new TxTcFileAttachmentData(str1, str3);
          new TxPlanningObjectEx(planningRepresantation).AttachEndModelingFilesOnObject(this.m_object, (TxFileAttachmentData) fileAttachmentData);
        }
        TxApplication.ActiveDocument.UndoManager.ClearAllTransactions();
      }
      catch (Exception ex)
      {
        TxApplication.LogWriter.WriteExceptionLine(ex);
        string str = new ResourceManager("DnProcessSimulateCommands.StringTable", ((object) this).GetType().Assembly).GetString("END_MODELING_CMD_NAME");
        int num = (int) TxMessageBox.Show(ex.Message, str, MessageBoxButtons.OK, MessageBoxIcon.Hand);
      }
    }
    Cursor.Current = current;
  }

  private ITxPlanningObject GetPlanningRepresantation(ITxObject obj)
  {
    switch (obj)
    {
      case ITxProcessModelObject processModelObject:
        pattern_0 = processModelObject.PlanningRepresentation;
        break;
    }
    return pattern_0;
  }

  private void m_process_SelectionChanged(object sender, EventArgs e)
  {
    if (this.m_process.Object == null)
      return;
    this.m_okButton.Enabled = true;
  }

  private void SaveDialogConfiguration()
  {
    TxFormSettings.StoreFormValue((Form) this, "CheckedRadioButton", (object) (!this.m_editJtOnObject.Checked ? (!this.m_editJtOnProcess.Checked ? 2 : 1) : 0).ToString());
  }

  private CUiTcEndModelingForm.EndModelingType LoadDialogConfiguration()
  {
    bool flag = false;
    if (this.m_object is ITxProcessModelObject processModelObject && processModelObject.PlanningRepresentation is TxPlanningPart)
      flag = true;
    object s = (object) null;
    TxFormSettings.RestoreFormValue((Form) this, "CheckedRadioButton", ref s);
    CUiTcEndModelingForm.EndModelingType endModelingType;
    if (s != null)
    {
      endModelingType = (CUiTcEndModelingForm.EndModelingType) int.Parse(s as string);
      if (flag && endModelingType == CUiTcEndModelingForm.EndModelingType.JtOnObject)
        endModelingType = CUiTcEndModelingForm.EndModelingType.JtOnProcess;
    }
    else
      endModelingType = !flag ? CUiTcEndModelingForm.EndModelingType.JtOnObject : CUiTcEndModelingForm.EndModelingType.JtOnProcess;
    return endModelingType;
  }

  protected virtual void Dispose(bool disposing)
  {
    if (disposing && this.components != null)
      this.components.Dispose();
    base.Dispose(disposing);
  }

  private void InitializeComponent()
  {
    ComponentResourceManager componentResourceManager = new ComponentResourceManager(typeof (CUiTcEndModelingForm));
    this.m_editJtOnObject = new RadioButton();
    this.m_editJtOnProcess = new RadioButton();
    this.m_txt = new Label();
    this.m_process = new TxObjComboBoxCtrl();
    this.m_reloadComponent = new RadioButton();
    this.m_cancelButton = new Button();
    this.m_okButton = new Button();
    ((Control) this).SuspendLayout();
    componentResourceManager.ApplyResources((object) this.m_editJtOnObject, "m_editJtOnObject");
    this.m_editJtOnObject.Name = "m_editJtOnObject";
    this.m_editJtOnObject.TabStop = true;
    this.m_editJtOnObject.UseVisualStyleBackColor = true;
    componentResourceManager.ApplyResources((object) this.m_editJtOnProcess, "m_editJtOnProcess");
    this.m_editJtOnProcess.Name = "m_editJtOnProcess";
    this.m_editJtOnProcess.TabStop = true;
    this.m_editJtOnProcess.UseVisualStyleBackColor = true;
    this.m_editJtOnProcess.CheckedChanged += new EventHandler(this.m_editJtOnProcess_CheckedChanged);
    componentResourceManager.ApplyResources((object) this.m_txt, "m_txt");
    this.m_txt.Name = "m_txt";
    this.m_process.DropDownHeight = 106;
    this.m_process.DropDownStyle = ComboBoxStyle.DropDown;
    this.m_process.ListenToPick = true;
    componentResourceManager.ApplyResources((object) this.m_process, "m_process");
    ((Control) this.m_process).Name = "m_process";
    this.m_process.Object = (ITxObject) null;
    this.m_process.PickLevel = (TxPickLevel) 1;
    this.m_process.ValidatorType = (TxValidatorType) 0;
    this.m_process.SelectionChanged += new EventHandler(this.m_process_SelectionChanged);
    this.m_process.TypeInvalid += new EventHandler(this.m_process_TypeInvalid);
    this.m_process.TypeValid += new EventHandler(this.m_process_TypeValid);
    this.m_process.Picked += new TxObjComboBoxCtrl_PickedEventHandler(this.m_process_Picked);
    componentResourceManager.ApplyResources((object) this.m_reloadComponent, "m_reloadComponent");
    this.m_reloadComponent.Name = "m_reloadComponent";
    this.m_reloadComponent.TabStop = true;
    this.m_reloadComponent.UseVisualStyleBackColor = true;
    componentResourceManager.ApplyResources((object) this.m_cancelButton, "m_cancelButton");
    this.m_cancelButton.Name = "m_cancelButton";
    this.m_cancelButton.UseVisualStyleBackColor = true;
    this.m_cancelButton.Click += new EventHandler(this.m_cancelButton_Click);
    componentResourceManager.ApplyResources((object) this.m_okButton, "m_okButton");
    this.m_okButton.Name = "m_okButton";
    this.m_okButton.UseVisualStyleBackColor = true;
    this.m_okButton.Click += new EventHandler(this.m_okButton_Click);
    componentResourceManager.ApplyResources((object) this, "$this");
    ((ContainerControl) this).AutoScaleMode = AutoScaleMode.Font;
    ((Control) this).Controls.Add((Control) this.m_okButton);
    ((Control) this).Controls.Add((Control) this.m_cancelButton);
    ((Control) this).Controls.Add((Control) this.m_reloadComponent);
    ((Control) this).Controls.Add((Control) this.m_process);
    ((Control) this).Controls.Add((Control) this.m_txt);
    ((Control) this).Controls.Add((Control) this.m_editJtOnProcess);
    ((Control) this).Controls.Add((Control) this.m_editJtOnObject);
    ((Form) this).FormBorderStyle = FormBorderStyle.FixedDialog;
    ((Form) this).MaximizeBox = false;
    ((Form) this).MinimizeBox = false;
    ((Control) this).Name = nameof (CUiTcEndModelingForm);
    ((Form) this).ShowIcon = false;
    ((Form) this).FormClosed += new FormClosedEventHandler(this.CUiTcEndModelingForm_FormClosed);
    ((Control) this).ResumeLayout(false);
    ((Control) this).PerformLayout();
  }

  public enum EndModelingType
  {
    JtOnObject,
    JtOnProcess,
    Reload,
  }
}
